<?php
// 应用公共文件
namespace app;
class Common {

    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    //下载csv文件
    static function downCsv($fileName, $csvBody) {


    }


    /**
     *name:导出对账失败的结果
     * log: 2018/12/21 0021
     * Author:long
     */
    static function order_query_csv($header,$data,$fileName) {
        // 处理头部标题
        $header = implode(',', $header) . PHP_EOL;
        $content = '';

        foreach ($data as $row) {
            $content.=implode(",",array_values($row)).PHP_EOL;
        }

        // 拼接
        $csv = $header . $content;
        Common::downCsv($fileName.".csv", $csv);
    }



/**
 * 导出excel(csv)
 * @data 导出数据
 * @headlist 第一行,列名
 * @fileName 输出Excel文件名
 */

static function csv_export($data = array(), $headlist = array(), $fileName) {

     header('Content-Type: application/vnd.ms-excel');
     header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
     header('Cache-Control: max-age=0');

    //打开PHP文件句柄,php://output 表示直接输出到浏览器
    $fp = fopen('php://output', 'a');

    //输出Excel列名信息
    foreach ($headlist as &$value) {
        //CSV的Excel支持GBK编码，一定要转换，否则乱码
        $value = iconv('utf-8', 'GBK//IGNORE', $value);
    }

    //将数据通过fputcsv写到文件句柄
    fputcsv($fp, $headlist);  

    foreach($data as $row){
        foreach($row as &$value){
            $value = iconv('utf-8', 'GBK//IGNORE', $value);
            //$value = mb_convert_encoding($value,"GBK","UTF-8");
        }
        fputcsv($fp, $row); 

    }

    exit; 
  }



    static function img_list($upload_dir){

        if(!$upload_dir) return 'Error';

        $upload_dir=str_replace("[*]","/",$upload_dir);
        echo $upload_dir;

        $files = scandir($upload_dir);

        foreach ($files as $file) {
            $file2 = "/".$upload_dir."/".$file;
            echo $file2.",".is_file($file2)."</br/>";
            if (is_file($file2) && $file2 != '.' && $file2 != '..') {
                echo '<img src="'. $file2 . '" style="width:100px;margin-right:10px;" alt="' . $file . '"  />';
            }else{
                echo '<a href="/admin/img_list/upload_dir/'.$file2.'">'.$file."</a><br/>";
            }
        }
    }

    //删除文件
    static function rm_file($file=null){
        if(!$file) return 0;

        $files = explode(",",$file);
        $cnt=0;
        foreach($files as $file){
            $fn = public_path().$file; 
            if(is_file($fn)){
                unlink($fn);
            }
        }

        return $cnt;
    }


    //通用的上传方法
    public function upload_x(){
        $files = $_FILES;
        if(count($files)<1) return json(['code'=>0,'msg'=>'Error!']);

        $res =[];
        foreach($files as $file){
            $res[] =$this->upload($file);
        }

        return $res;
    }

    //文件上传处理
    static function upload($file=null){
        // 允许上传的图片后缀
        $allowedExts = array("gif", "jpeg", "jpg", "png","csv");
        if(!$file) $file=$_FILES['file'];

        $temp = explode(".", $file["name"]); //无参，单个文件上传
        $extension = end($temp);     // 获取文件后缀名

        if($extension!="csv" && $file["size"] > (1024*1024*2)){
            return array('code'=>0,'msg'=>"上传失败,图片文件不能超过2MB！");
        }elseif($file["size"] > (1024*1024*4)){
            return array('code'=>0,'msg'=>"上传失败,数据文件不能超过2MB！");
        }

        if ((($file["type"] == "text/csv")
        || ($file["type"] == "image/gif")
        || ($file["type"] == "image/jpeg")
        || ($file["type"] == "image/jpg")
        || ($file["type"] == "image/pjpeg")
        || ($file["type"] == "image/x-png")
        || ($file["type"] == "image/png"))
        && in_array($extension, $allowedExts)){
            if ($file["error"] > 0){
                return ['code'=>0,"msg"=> $file["error"]];
            }else{
                $msg =[];
                $msg[] = array("File name" => $file["name"]);
                $msg[] = array('File type' => $file["type"]);
                $msg[] = array('File size' => $file["size"]/1024);
                $msg[] = array('Tmp name' => $file["tmp_name"]);
                 
                // 判断当期目录下的 upload 目录是否存在该文件
                // 如果没有 upload 目录，你需要创建它，upload 目录权限为 777
                if($extension=="csv"){
                    $folder="upload/excel";
                    return ['code'=>1,'msg'=>$file["tmp_name"]];
                }else{
                    $folder="upload/".date("Ymd");
                }

                $targetPath = public_path(). $folder;

                if(!file_exists($targetPath)){
                    mkdir($targetPath,0777,1);
                    chmod($targetPath,0777);
                }

                $fn = md5($file['name'].time()).".".$extension;
                move_uploaded_file($file["tmp_name"], $targetPath."/" . $fn);
                return ['code'=>'1', 'msg'=>"/".$folder."/". $fn];
            }
        }else{
            return array('code'=>0,'msg'=>"非法的文件格式");
        }
    }

    /**
     * 验证手机号
     * @param $mobile
     * @return bool
     */
    static function is_mobile($mobile){
        if(empty($mobile)) return 0;
        if (strlen($mobile) == "11") {
            //上面部分判断长度是不是11位
            $phone_pattern = "/^1[356789]{1}\d{9}$/"; //1+[3,5,6,7,8,9]+9位数
            $n = preg_match_all($phone_pattern,$mobile);
            return $n;
        } else {
            return 0;
        }
    }


    //随机字符串
    static function randomString($length = 10) { 
      $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
      $randStr = ''; 
      for ($i = 0; $i < $length; $i++) { 
        $randStr .= $characters[rand(0, strlen($characters) - 1)]; 
      } 
      return $randStr; 
    }

    //时间美化
    static function time_format($second=0){
        if(!$second || $second<0) return '已过期';

        $days = floor($second/3600/24);
        if($days) return $days."天";

        $hours = floor($second/3600);
        if($hours<1) $hours=0;

        $minutes  = floor(($second%3600)/60);
        if($minutes<1) $minutes =0;

        return $hours."小时".$minutes."分";

    }

    //curl_post method
    static function curl_post($url, $param){
        $curl = curl_init();
        $headers = ['Accept:application/json','Content-Type:application/json;charset=utf-8'];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_POST, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }



    

}